#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-05-23 12:20
# @Author   : BYF
# file      : log.py
# @version  :


import logging
import logging.config
import logging.handlers
import datetime
from lefull.conf.config import Config


class Log():
    """
    日志模块
    """

    def __init__(self):
        """
        初始化，自定义实现
        """
        self.config = Config()
        self.logger = logging.getLogger("lefull")
        self.logger.setLevel(logging.DEBUG)
        self.log_dir = self.config.log_dir
        self.LOG_FORMAT = "%(asctime)s -%(levelname)s- %(message)s"
        self.DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

    def create_handler(self, log_name):
        """
        创建handler
        :param log_name:
        :return:
        """
        log_name = "{log_dir}/{log_name}".format(log_dir=self.config.log_dir, log_name=log_name)
        handler = logging.handlers.TimedRotatingFileHandler(
            log_name,
            when="midnight",  # midnight 为凌晨进行日志 切割
            interval=1,
            backupCount=10,  # 设置日志文件最大数
            atTime=datetime.time(0, 0, 0, 0)
        )

        handler.setLevel(logging.DEBUG)
        # 设置日志格式
        LOG_FORMAT = self.LOG_FORMAT
        DATE_FORMAT = self.DATE_FORMAT
        handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT))
        return handler

    def add_handler(self, handler):
        """
        添加handler
        :param handler:
        :return:
        """
        self.logger.addHandler(handler)

    def remove_handler(self, handler):
        """
        删除handler
        :param handler:
        :return:
        """
        self.logger.removeHandler(handler)

    def console(self, message):
        """
        将日志消息发送到输出到Stream
        :return:
        """
        c_handler = logging.StreamHandler()
        c_handler.setLevel(logging.ERROR)
        LOG_FORMAT = self.LOG_FORMAT
        DATE_FORMAT = self.DATE_FORMAT
        c_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT))
        self.logger.addHandler(c_handler)
        self.logger.info(message)
        self.logger.removeHandler(c_handler)


log = Log()


def debug(message, log_name="log.log"):
    handler = log.create_handler(log_name)
    log.add_handler(handler)
    log.logger.debug(message)
    log.remove_handler(handler)


def info(message, log_name="log.log"):
    handler = log.create_handler(log_name)
    log.add_handler(handler)
    log.logger.info(message)
    log.remove_handler(handler)


def warning(message, log_name="log.log"):
    handler = log.create_handler(log_name)
    log.add_handler(handler)
    log.logger.warning(message)
    log.remove_handler(handler)


def error(message, log_name="log.log"):
    handler = log.create_handler(log_name)
    log.add_handler(handler)
    log.logger.error(message)
    log.remove_handler(handler)


def critical(message, log_name="log.log"):
    handler = log.create_handler(log_name)
    log.add_handler(handler)
    log.logger.critical(message)
    log.remove_handler(handler)


def case_log(case_name, url, headers, payload, response):
    """
    用例日志
    :param case_name:
    :param url:
    :param payload:
    :param result:
    :return:
    """
    handler = log.create_handler("log.log")
    log.add_handler(handler)
    log.logger.info("============  {case_name}   START ============".format(case_name=case_name))
    log.logger.info("接口请求地址为：{url}".format(url=url))
    log.logger.info("接口头为：{headers}".format(headers=headers))
    log.logger.info("接口请求参数为：{payload}".format(payload=payload))
    log.logger.info("接口返回结果为：{response}".format(response=response))
    log.logger.info("============  {case_name}   END ============".format(case_name=case_name))
    log.remove_handler(handler)
